const tools = require('../common/tools');
const dbUtil = require('../model/dbUtil');
const config = require('../config');
const dateFormat = require('dateformat');
const { request } = require('express');

//管理员用户名
async function getAdminInfo(req, res) {
    !req.session.currentUser && res.send({ code: 400, adminInfo: '' });
    let { uid } = req.session.currentUser;
    let sql = "select * from users where user_id=?";
    let params = [uid];
    let result = await dbUtil.asyncQuery(sql, params);
    if (result.length > 0) {
        delete result[0].user_pwd;
        if (result[0].user_role == "admin" && result[0].user_state == "Y") {
            res.send({ code: 200, adminInfo: result[0].user_name });
        }
    }
}

//登录页
function loginPage(req, res) {
    res.render('admin/rootlogin')
}

//用户登录
function doLogin(req, res) {
    let { user_name, user_pwd } = req.body;
    console.log(user_name, user_pwd);

    let sql = '';
    if (Number(user_name) && Number(user_name) == 11) {
        sql = "select * from users where user_phone=? and user_pwd=?";
    } else {
        sql = "select * from users where user_name=? and user_pwd=?";
    }
    let parsms = [user_name, user_pwd];
    console.log(parsms);
    dbUtil.query(sql, parsms, (err, results) => {
        if (err) {
            console.log(err.message);
            res.render('error', { error: "服务器出错 404..." });
        } else {
            if (results.length > 0) {
                if (results[0].user_state == "Y" && results[0].user_role == "admin") {
                    req.session.currentUser = { uname: results[0].user_name, uid: results[0].user_id, userRole: results[0].user_role };
                    let data = {
                        code: 200,
                        username: user_name,
                        message: '登陆成功',
                        href: '/admin/user'
                    }
                    res.send(data);

                } else {
                    let data = {
                        code: 400,
                        message: '账号已被禁用',
                    }
                    res.send(data);
                }
            } else {
                let data = {
                    code: 400,
                    message: '账号或密码错误',
                }
                res.send(data);
            }
        }
    });
}

//用户管理页
async function userPage(req, res) {
    let isActive = "user";
    let count = 0, //数据总条数
        // 接收客户端传递过来的当前页参数
        page = req.query.Page || 1; //默认第一页

    {
        let sql = "select count(*) as total from users";
        let params = [];
        count = await dbUtil.asyncQuery(sql, params);
        count = count[0].total;
        // console.log(count);
    }

    // 每一页显示的数据条数
    let pageSize = config.pageSize;
    // 总页数
    let total = Math.ceil(count / pageSize);
    // 页码对应的数据查询开始位置
    let start = (page - 1) * pageSize;

    //客户端展示的页码数
    let getPage = tools.layPage(page, 5, total);
    // console.log(getPage);
    let sql = `select us.*,uw.* from users us,user_wallet uw
                where us.user_id = uw.user_id
                ORDER BY us.user_id DESC limit ?,?`;
    let params = [start, pageSize];
    let result = await dbUtil.asyncQuery(sql, params);
    // console.log(result);
    res.render('admin/user', {
        data: result,
        page,
        total,
        userCount: count,
        getPage,
        dateFormat,
        isActive
    });
}

//用户信息编辑页
function userEditPage(req, res) {
    let isActive = "user";
    let user_id = req.query.userId;
    let sql = `select * from users us,user_wallet uw
                where us.user_id = uw.user_id
                and us.user_id=${user_id}`;
    dbUtil.query(sql, [], (err, result) => {
        if (err) {
            return console.log(err.message);
        } else {
            // console.log(result);
            res.render('admin/user-edit', { userInfo: result[0], isActive });
        }
    })
}

//用户信息修改
function userInfoUpdate(req, res) {
    console.log(req.body);
    //获取用户信息
    let { user_id, user_nickname, user_phone } = req.body;
    let { user_email, user_pwd, user_role, user_state, money } = req.body;
    let sql = `update users set user_nickname=?,user_phone=?,user_email=?,user_pwd=?,user_role=?,user_state=? where user_id=${user_id};
                update user_wallet set money=? where user_id=${user_id};`;
    let params = [user_nickname, user_phone, user_email, user_pwd, user_role, user_state, money]
    dbUtil.query(sql, params, (err, result) => {
        if (err) {
            console.log(err.message);
            res.redirect('/userEditPage');
        } else {
            console.log(result);
            res.redirect('/admin/user');
        }
    })
}

//添加用户页
function userAddPage(req, res) {
    let isActive = "user";
    res.render('admin/user-add', { isActive });
}

//添加用户
async function userAdd(req, res) {
    console.log(req.body);

    let { user_name, user_pwd, suc_pwd, user_phone } = req.body;
    // console.log(user_name, user_pwd, suc_pwd);
    let flag = await userExist(user_name);
    //console.log(flag);
    //用户存在
    if (flag) {
        let data = {
            code: 300,
            message: '用户已被注册'
        }
        res.send(data);
    } else {
        //生成用户昵称
        let user_nickname = '用户' + String(Date.now()).substr(6, );
        let sql = ` begin;
                    insert into users(user_nickname,user_name,user_pwd,user_phone) values(?,?,?,?);
                    insert into user_wallet set user_id=(select user_id from users where user_name=?);
                    commit;
                    rollback;
                    `;
        let params = [user_nickname, user_name, user_pwd, user_phone, user_name];

        if (user_pwd.trim() == suc_pwd.trim()) {
            dbUtil.query(sql, params, async(err, result) => {
                if (err) {
                    console.log(err.message);
                    res.render('error', { error: "服务器出错 404..." });
                    //res.send({ code: 404, message: "服务器出错 404..." });
                } else {
                    if (result) {
                        let data = {
                            code: 200,
                            message: "注册成功",
                            href: '/admin/user',
                            userInfo: user_name
                        }
                        console.log(data);
                        res.send(data);
                    } else {
                        let data = {
                            code: 400,
                            message: "注册失败",
                        }
                        console.log(data);
                        res.send(data);
                    }
                }
            })
        } else {
            let data = {
                code: 400,
                message: '账号或密码错误，注册失败'
            }
            res.send(data);
        }
    }
}

//私有方法 判断用户是否已被注册
function userExist(username) {
    return new Promise((resolve, reject) => {
        let sql = "select * from users where user_name=?";
        let params = [username];
        dbUtil.query(sql, params, (err, result) => {
            if (err) {
                reject(err.message);
            } else {
                if (result.length > 0) {
                    resolve(true); //用户存在
                } else {
                    resolve(false); //用户不存在
                }
            }
        })
    });
}

//删除用户
function userDel(req, res) {
    console.log("------------------------------");
    let { user_id } = req.body;
    if (!user_id) {
        res.redirect('/admin/user');
    }
    isAdmin(user_id).then(flag => {
        if (flag) {
            console.log("管理员账号不能删除");
            res.redirect('/admin/user');
        } else {
            let sql = `delete from good_comment where user_id=${user_id};
                        delete from user_address where user_id=${user_id};
                        delete from user_wallet where user_id=${user_id};
                        delete from user_cart where user_id=${user_id};
                        delete from users where user_id=${user_id};`;
            dbUtil.query(sql, [], (err, result) => {
                if (err) {
                    console.log(err.message);
                } else {
                    // console.log(result);
                    res.redirect('/admin/user');
                }
            })
        }
    })
}

//私有方法 判断是不是 admin 管理员 如果是将不能删除管理员
function isAdmin(userId) {
    let sql = `select * from users where user_id=${userId}`;
    return new Promise((resolve, reject) => {
        dbUtil.query(sql, [], (err, result) => {
            if (err) {
                reject(err);
            } else {
                if (result[0].user_role == "admin") {
                    resolve(true); //是管理员
                } else {
                    resolve(false); //是普通用户
                }
            }
        })
    })
}

//商品列表 
async function goods(req, res) {
    let isActive = "goods";
    let count = 0, //数据总条数
        // 接收客户端传递过来的当前页参数
        page = req.query.Page || 1; //默认第一页

    {
        let sql = `select * from good_class gcl,goods gs,good_attr gt,good_count gc
        where gcl.cls_id=gs.cls_id
        and gs.g_id=gt.g_id
        and gt.attr_id=gc.attr_id`;
        let params = [];
        count = await dbUtil.asyncQuery(sql, params);
        count = count.length;
        // console.log(count);
    }

    // 每一页显示的数据条数
    let pageSize = config.pageSize;
    // 总页数
    let total = Math.ceil(count / pageSize);
    // 页码对应的数据查询开始位置
    let start = (page - 1) * pageSize;

    //客户端展示的页码数
    let getPage = tools.layPage(page, 5, total);
    // console.log(getPage);


    let sql = `select * from  good_class gcl,goods gs,good_attr gt,good_count gc
                where gcl.cls_id=gs.cls_id
                and gs.g_id=gt.g_id
                and gt.attr_id=gc.attr_id
                ORDER BY gs.s_issued DESC limit ?,?;`;
    let params = [start, pageSize];
    let result = await dbUtil.asyncQuery(sql, params);
    // console.log(result);
    res.render('admin/article', {
        data: result,
        page,
        total,
        goodCount: count,
        getPage,
        dateFormat,
        isActive
    });
}

//商品编辑页
function goodEditPage(req, res) {
    let isActive = "goods";
    let { g_id } = req.query;
    let sql = `select * from good_class;
                select * from  good_class gcl,goods gs,good_attr gt,good_count gc
                where gcl.cls_id=gs.cls_id
                and gs.g_id=gt.g_id
                and gt.attr_id=gc.attr_id
                and gs.g_id='${g_id}';`;

    dbUtil.query(sql, [], (err, result) => {
        if (err) {
            console.log(err.message);
        } else {
            // console.log(result[1]);

            res.render('admin/article-edit', {
                goodClass: result[0],
                goodInfo: result[1][0],
                isActive
            });
        }
    })

}

//商品编辑（信息更新）
function goodEdit(req, res) {
    //商品信息表数据
    let { cls_id, g_id, g_name, g_desc, g_price, g_stat } = req.body;
    //属性表信息
    let { attr_title, attr_item } = req.body;
    //商品库存表
    let { g_num } = req.body;

    let filePath = ''; //用于保存商品封面图片地址
    console.log(req.file);

    let sql = `update goods set cls_id=?,g_name=?,g_desc=?, g_price=?, g_stat=? where g_id='${g_id}';
                update good_attr set attr_title=?,attr_item=? where g_id='${g_id}';
                update good_count set g_num=? where g_id='${g_id}';`;
    let params = [cls_id, g_name, g_desc, g_price, g_stat, attr_title, attr_item, g_num];


    //判断是否上传商品封面图文件
    if (req.file) {
        filePath = req.file.path.split('public')[1]; // 打印 \uploads\20201113\1605261036242.jpg
        sql = `update goods set cls_id=?,g_name=?,g_desc=?, g_price=?,g_show_img=?,g_stat=? where g_id='${g_id}';
                update good_attr set attr_title=?,attr_item=? where g_id='${g_id}';
                update good_count set g_num=? where g_id='${g_id}';`;
        params = [cls_id, g_name, g_desc, g_price, filePath, g_stat, attr_title, attr_item, g_num];
    }
    dbUtil.query(sql, params, (err, result) => {
        if (err) {
            console.log(err.message);
        } else {
            console.log(result);
            //返回商品管理页
            res.redirect('/admin/goods');
        }
    })
}

//上架新商品页
function goodAddPage(req, res) {
    let isActive = "goods";
    let sql = "select * from good_class";
    dbUtil.query(sql, [], (err, result) => {
        if (err) {
            console.log(err.message);
        } else {
            console.log(result);
            res.render('admin/article-add', { goodClass: result, isActive })
        }
    })

}

//上架新商品
async function goodAdd(req, res) {
    console.log(req.body);
    //生成商品id
    let g_id = await tools.encryption(Math.random(), 'g');
    // console.log(g_id);
    //商品信息表数据
    let { cls_id, g_name, g_desc, g_price } = req.body;
    g_price = parseFloat(g_price).toFixed(2); //处理价格

    //属性表信息
    let { attr_title, attr_item } = req.body;
    //商品库存表
    let { g_num } = req.body;

    let filePath = ''; //用于保存商品展示图片地址
    if (req.file) {
        filePath = req.file.path.split('public')[1]; // 打印 \uploads\20201113\1605261036242.jpg     
    } else {
        filePath = '/';
    }
    let sql = `insert into goods(g_id,cls_id,g_name,g_desc,g_price,g_show_img) 
                values(?,?,?,?,?,?);
            insert into good_attr(g_id,attr_title,attr_item) values(?,?,?);`;
    let params = [g_id, cls_id, g_name, g_desc, g_price, filePath, g_id, attr_title, attr_item];

    let addGoodRs = await dbUtil.asyncQuery(sql, params);
    console.log(addGoodRs);
    if (addGoodRs) {
        //商品插入成功
        let attr_id = addGoodRs[1].insertId;
        console.log(attr_id);
        //商品插入成功，插入库存数据
        sql = 'insert into good_count(attr_id, g_id, g_num) values(?,?,?)';
        params = [attr_id, g_id, g_num];

        let endResult = await dbUtil.asyncQuery(sql, params);
        res.redirect('/admin/goods');
    } else {
        //商品插入失败
        res.redirect('/admin/goodAddPage');
    }
}

//删除商品
function goodDel(req, res) {
    console.log(req.body);

    let { g_id } = req.body;

    let sql = `delete from good_count where g_id='${g_id}';
                delete from good_attr where g_id='${g_id}';
                delete from goods where g_id='${g_id}';`
    dbUtil.query(sql, [], (err, result) => {
        if (err) {
            console.log("商品删除失败");
            console.log(err.message);
        } else {
            res.redirect('/admin/goods');
        }
    });
}

//订单列表页
async function orderListPage(req, res) {
    let isActive = "order";
    let count = 0, //数据总条数
        // 接收客户端传递过来的当前页参数
        page = req.query.Page || 1; //默认第一页

    {
        let sql = `select * from user_order_list`;
        let params = [];
        count = await dbUtil.asyncQuery(sql, params);
        count = count.length;
        // console.log(count);
    }

    // 每一页显示的数据条数
    let pageSize = 10;
    // 总页数
    let total = Math.ceil(count / pageSize);
    // 页码对应的数据查询开始位置
    let start = (page - 1) * pageSize;

    //客户端展示的页码数
    let getPage = tools.layPage(page, 5, total);
    // console.log(getPage);

    let sql = `select us.user_name,ol.*,gs.g_name from users us,user_order_list ol,goods gs
                where us.user_id=ol.user_id
                and ol.g_id=gs.g_id
                ORDER BY ol.order_id DESC limit ?,?;`;
    let params = [start, pageSize];
    let result = await dbUtil.asyncQuery(sql, params);
    // console.log(result);
    res.render('admin/order-list', {
        data: result,
        page,
        total,
        orderCount: count,
        getPage,
        dateFormat,
        isActive
    });
}

//处理发货
function orderDeliver(req, res) {
    let { order_num } = req.body;
    let sql = `update user_order_list set order_deliver='T' where order_num='${order_num}';`;

    dbUtil.query(sql, [], (err, result) => {
        if (err) {
            console.log(err.message);
        } else {
            res.redirect('/admin/orderList');
        }
    })
}

function adminExit(req, res) {
    // 删除session
    req.session.destroy(function() {
        // 删除cookie
        res.clearCookie('connect.sid');
        // 重定向到用户登录页面
        res.redirect('/admin/login');
    });
}

module.exports = {
    getAdminInfo,
    loginPage,
    doLogin,
    userPage,
    userEditPage,
    userInfoUpdate,
    userDel,
    userAddPage,
    userAdd,
    goods,
    goodEditPage,
    goodEdit,
    goodAddPage,
    goodAdd,
    goodDel,
    orderListPage,
    orderDeliver,
    adminExit
}